<template>
  <!-- AI助手悬浮按钮 -->
  <div v-if="showAIAssistant" class="fixed bottom-2 right-16 md:bottom-10 md:right-24 z-50">
    <!-- 悬浮按钮 -->
    <el-button
      @click="toggleDrawer"
      type="primary"
      :icon="isDrawerOpen ? Close : ChatDotRound"
      circle
      size="large"
      class="shadow-lg hover:shadow-xl transition-all duration-300"
    />

    <!-- Element Plus 抽屉组件 -->
    <el-drawer
      v-model="isDrawerOpen"
      title="AI 助手"
      :size="drawerSize"
      direction="rtl"
      :modal="true"
      :close-on-click-modal="true"
      :close-on-press-escape="true"
      :modal-class="'ai-assistant-modal'"
      class="ai-assistant-drawer"
    >
      <!-- 聊天内容区域 -->
      <div class="flex flex-col h-full">
        <!-- 聊天消息区域 -->
        <div class="flex-1 overflow-y-auto p-4 bg-gray-50 dark:bg-gray-800">
          <!-- 空状态 -->
          <el-empty 
            v-if="messages.length === 0" 
            description="开始与AI助手对话吧！"
            :image-size="80"
          >
            <template #image>
              <el-icon size="80" class="text-gray-300 dark:text-gray-600">
                <ChatDotRound />
              </el-icon>
            </template>
          </el-empty>
          
          <!-- 消息列表 -->
          <div v-for="message in messages" :key="message.id" class="mb-4">
            <!-- 用户消息 -->
            <div v-if="message.type === 'user'" class="flex justify-end">
              <el-card 
                class="max-w-xs bg-blue-500 text-white border-0" 
                shadow="never"
                body-style="padding: 12px 16px;"
              >
                {{ message.content }}
              </el-card>
            </div>
            <!-- AI回复 -->
            <div v-else class="flex justify-start">
              <el-card 
                class="max-w-xs" 
                shadow="never"
                body-style="padding: 12px 16px;"
              >
                {{ message.content }}
              </el-card>
            </div>
          </div>

          <!-- 加载状态 -->
          <div v-if="isLoading" class="flex justify-start mb-4">
            <el-card 
              class="max-w-xs" 
              shadow="never"
              body-style="padding: 12px 16px;"
            >
              <div class="flex items-center space-x-2">
                <el-icon class="animate-spin">
                  <Loading />
                </el-icon>
                <span class="text-gray-500">AI正在思考中...</span>
              </div>
            </el-card>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="p-4 border-t border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900">
          <el-input
            v-model="newMessage"
            type="textarea"
            :rows="2"
            placeholder="输入您的问题..."
            :disabled="isLoading"
            @keyup.enter.ctrl="sendMessage"
            @keyup.enter.meta="sendMessage"
            resize="none"
            class="mb-3"
          />
          <div class="flex justify-end">
            <el-button
              @click="sendMessage"
              type="primary"
              :disabled="!newMessage.trim() || isLoading"
              :loading="isLoading"
              :icon="Promotion"
            >
              发送
            </el-button>
          </div>
        </div>
      </div>
    </el-drawer>
  </div>
</template>

<script setup>
import { computed, ref, onMounted, onUnmounted } from 'vue'
import { useBlogSettingsStore } from '@/stores/blogsettings'
import { sendAIMessage } from '@/api/frontend/ai'
import { 
  ChatDotRound, 
  Close, 
  Loading, 
  Promotion 
} from '@element-plus/icons-vue'

const blogSettings = useBlogSettingsStore()

// 计算属性：是否显示AI助手
const showAIAssistant = computed(() => {
  console.log('博客设置数据:', blogSettings.blogSettings)
  console.log('aiTalk字段值:', blogSettings.blogSettings?.aiTalk)
  
  // 确保aiTalk字段为true时才显示
  return blogSettings.blogSettings?.aiTalk === true || blogSettings.blogSettings?.aiTalk === 'true'
})

// 响应式数据
const isDrawerOpen = ref(false)
const messages = ref([])
const newMessage = ref('')
const isLoading = ref(false)

// 计算抽屉大小 - 移动端适配
const drawerSize = computed(() => {
  // 检测是否为移动设备
  const isMobile = window.innerWidth < 768
  return isMobile ? '100%' : '380px'
})

// 方法
const toggleDrawer = () => {
  isDrawerOpen.value = !isDrawerOpen.value
}

const closeDrawer = () => {
  isDrawerOpen.value = false
}

const sendMessage = async () => {
  if (!newMessage.value.trim() || isLoading.value) return

  const userMessage = {
    id: Date.now(),
    type: 'user',
    content: newMessage.value.trim(),
    timestamp: new Date()
  }

  messages.value.push(userMessage)
  const currentMessage = newMessage.value.trim()
  newMessage.value = ''
  isLoading.value = true

  try {
    // 调用真实的AI API
    const response = await sendAIMessage(currentMessage)
    
    const aiMessage = {
      id: Date.now() + 1,
      type: 'ai',
      content: response.data.message || response.data.reply || '收到您的消息，正在处理中...',
      timestamp: new Date()
    }
    
    messages.value.push(aiMessage)
  } catch (error) {
    console.error('AI API调用失败:', error)
    
    // 降级方案：提供模拟回复
    const fallbackMessage = {
      id: Date.now() + 1,
      type: 'ai',
      content: '抱歉，AI服务暂时不可用。这是一个模拟回复：我收到了您的消息"' + currentMessage + '"，感谢您的提问！',
      timestamp: new Date()
    }
    
    messages.value.push(fallbackMessage)
  } finally {
    isLoading.value = false
  }
}

// ESC键关闭抽屉
const handleEscKey = (event) => {
  if (event.key === 'Escape' && isDrawerOpen.value) {
    closeDrawer()
  }
}

// 组件挂载时添加键盘事件监听
onMounted(() => {
  document.addEventListener('keydown', handleEscKey)
})

// 组件卸载时移除键盘事件监听
onUnmounted(() => {
  document.removeEventListener('keydown', handleEscKey)
})
</script>

<style scoped>
/* Element Plus 抽屉自定义样式 */
:deep(.ai-assistant-drawer .el-drawer__body) {
  padding: 0;
  height: 100%;
}

:deep(.ai-assistant-drawer .el-drawer__header) {
  margin-bottom: 0;
  padding: 16px 20px;
  border-bottom: 1px solid var(--el-border-color-light);
}

/* PC端抽屉优化 */
@media (min-width: 768px) {
  :deep(.ai-assistant-drawer .el-drawer) {
    max-width: 380px;
    box-shadow: -4px 0 20px rgba(0, 0, 0, 0.15);
  }
  
  /* 减少遮罩层透明度，降低对页面内容的影响 */
  :deep(.ai-assistant-modal) {
    background-color: rgba(0, 0, 0, 0.3) !important;
  }
}

/* 移动端适配 */
@media (max-width: 768px) {
  :deep(.ai-assistant-drawer .el-drawer) {
    width: 100% !important;
  }
  
  :deep(.ai-assistant-drawer .el-drawer__header) {
    padding: 12px 16px;
  }
}

/* 消息卡片样式 */
:deep(.el-card.bg-blue-500) {
  background-color: #3b82f6 !important;
  border: none !important;
}

:deep(.el-card.bg-blue-500 .el-card__body) {
  color: white !important;
}

/* 黑暗模式适配 */
@media (prefers-color-scheme: dark) {
  :deep(.ai-assistant-drawer .el-drawer__header) {
    border-bottom-color: var(--el-border-color-darker);
  }
  
  @media (min-width: 768px) {
    :deep(.ai-assistant-modal) {
      background-color: rgba(0, 0, 0, 0.5) !important;
    }
  }
}
</style>